package com.kotlin.demo.tools

import java.io.*


object FileUtils {
    /**
     * 将字符串保存到文件中
     */
    private fun stringToFile(file: File, string: String?): Boolean {
        if (file.exists()) {
            file.delete()
        }
        var writer: BufferedWriter? = null
        try {
            file.createNewFile()
            val outputStreamWriter = OutputStreamWriter(FileOutputStream(file), "utf-8")
            writer = BufferedWriter(outputStreamWriter)
            writer.write(string!!)
            writer.flush()
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        } finally {
            if (writer != null) {
                try {
                    writer.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return true
    }

    /**
     * 写入文件
     */
    fun stringToFile(string: String) {
        val userHome = System.getProperty("user.home")
        // 构建桌面路径
        val file = File(userHome, "Desktop" + File.separator + "translate_config.json")
        stringToFile(file, string)
    }

    /**
     * 文件转json
     */
    fun fileToJson(): String {
        val userHome = System.getProperty("user.home")
        // 构建桌面路径
        val file = File(userHome, "Desktop" + File.separator + "translate_config.json")
        val stringBuilder = StringBuilder()
        if (file.exists()) {
            var reader: BufferedReader? = null
            try {
                reader = BufferedReader(FileReader(file))
                var line: String?
                while ((reader.readLine().also { line = it }) != null) {
                    stringBuilder.append(line)
                }
            } catch (e: java.lang.Exception) {
                println(e)
            } finally {
                if (reader != null) {
                    try {
                        reader.close()
                    } catch (e: IOException) {
                        println(e)
                    }
                }
            }
        } else {
            println("no file")
        }
        return stringBuilder.toString()
    }
}